﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain.Abstract;
using Domain.Entity;
using System.Data;

namespace Domain.Concrete
{
    public class EFGameRepository : IGameRepository
    {
        public EFDbContext Context { get; set; }

        public EFGameRepository()
        {
            Context = EFDbContext.Instance;
        }

        public EFGameRepository(EFDbContext context)
        {
            Context = context;
        }

        public IQueryable<Game> Games
        {
            get { return Context.Games.Include("Articles").Include("Platforms").Include("SystemRequirements").Include("MetaScores").Include("Pictures"); }
        }

        public IQueryable<Game> Search(string searchFor)
        {
            return null;
        }

        public void Save(Game g)
        {
            this.UpdatePopularValue(g);
            if (g.Id == 0)
                Context.Games.Add(g);
            else
                Context.Entry(g).State = EntityState.Modified;

            if (g.SystemRequirements != null)
            {
                if (g.SystemRequirements.Id == 0)
                    Context.SystemRequirementsDONOTUSE.Add(g.SystemRequirements);
                else
                    Context.Entry(g.SystemRequirements).State = EntityState.Modified;
            }

            Context.SaveChanges();
        }

        public Game FindById(int id)
        {
            Game game = Games.FirstOrDefault(x => x.Id == id);
            this.UpdatePopularValue(game);
            return game;
        }

        public void Delete(Game game)
        {
            var dbGame = Games.SingleOrDefault(x => x.Id == game.Id);

            if (dbGame != null)
                Context.Games.Remove(dbGame);

            Context.SaveChanges();
        }

        private void UpdatePopularValue(Game game)
        {
            int feedbackValue = game.Reviews.Sum(r => r.Feedbacks.Count);
            game.PopularGameValue = (int)(((game.AverageRating * .33) + (game.Reviews.Count * .33) + (feedbackValue * .33)) * 100.0);
        }
    }
}
